// packageC/pages/takeoutOrder/takeoutOrder.js
const app = getApp()
// var QQMapWX = require('../../utils/qqmap-wx-jssdk1.2/qqmap-wx-jssdk.min.js');
const QQMapWX = require('../../../libs/qqmap-wx-jssdk1.2/qqmap-wx-jssdk') //腾讯
var qqmapsdk;
const common = require('../../../public.js')
Page({
    /**
     * 页面的初始数据
     */
    data: {
        newLatitude:'',
        newLongitude:'',
        useCoupon:false,
        tempUseCoupon:false,
        cardVipJson:'',
        hasBuy:false,//已购买
        cardVipShow:false,
        memeberSelect:false,
        radioValue:"1",
        commentPlachold: '请输入备注信息如口味',
        commentValue:"",
        totalPostType:[
            // {"id":591,"dname":"外卖配送","storeId":1479,"feeType":"1","price":10.00,"createTime":1683534351000},
            // {"id":null,"dname":"到店自提","storeId":null,"feeType":"2","price":0,"createTime":null}
        ],
        height: '',
        top: '',
        activeII: 0,
        receiverAddress: '',
        receiverMobile: '',
        receiverName: '',
        storeInfo: '',
        goodList: [],
        totalPrice: 0,
        tempTotalPrice:0,
        totalPackingFee:0,
        isShow: false,
        selectDate: "",
        dialogh: 0,
        //日期列表和时间列表
        date_list: [],
        time_list: [],
        range: 0,
        start_time: 8,
        end_time: 22,
        step: 30,
        isTimeShow: false,
        hasSelectPAmount: 0,
        hasSelectCityPAmount: 0,
        selectedAddr: false,
        radio: 1,
        cardId: '',
        storePriceAddress: -1,
        items: [],
        counts: 0, //金豆数量
        cityCouponNo: '',
        discountCoupons: [],
        buyerMessage: "",
        remark: "",
        flags: true, //控制开关
        storePrice: 0,
        StoPrice: 0,
        tempStoPrice:0,
        statusTag: true,
        showStoreCoupons: false,
        checked: false,
        typeIndex: 0, //0是外卖配送 1自提
        postPrice: 0,
        fixedPostPrice:0,
        paramArr: [],
        addressLists: [],
        latitude: 23.096994,
        longitude: 113.324520,
        markers: [
            {
                id: 2,
                latitude: 23.098994,
                longitude: 113.322520,
                iconPath: 'http://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/icon/po.png',
                callout: {
                    content: '据您0.5km',
                    color: '#000',
                    fontSize: 14,
                    borderWidth: 2,
                    borderRadius: 10,
                    borderColor: '#ffff',
                    bgColor: '#fff',
                    padding: 5,
                    display: 'ALWAYS',
                    textAlign: 'center'
                },
            }
        ],
        customCalloutMarkerIds: [2],
        postType: 1,
        checkedTime:false

    },
    click_checkedTime(e) {
        let { item, index } = e.currentTarget.dataset
        let selectDate = item
        this.setData({
            selectDate,
            activeII: index
        })
    },
    onChecked(e) {
        this.setData({
            checked: e.detail,
        });
    },
    // 配送方式选择
    topChoice(e) {
        console.log(e, "jkkkkkkkkkkjjjjjjjjj")
        let typeIndex =Number(e.currentTarget.dataset.index)
        console.log(e.currentTarget.dataset,'ttttttttttttttttttt')
        console.log(typeIndex,"indexindex",this.data.postPrice)
        this.setData({
            typeIndex,
            statusTag: !this.data.statusTag,
            postType: typeIndex==0?1:2,
            postPrice: typeIndex==0?this.data.fixedPostPrice:0,
            postage:  typeIndex==0?this.data.fixedPostPrice:0,
        },()=>{
            console.log(this.data.postPrice,"pppppppppppppp")
        })
    },
    // 企业券确定
    ComPany_submit() {
        var that = this;
        console.log("打印却确定", this.data.totalPreferential)

        console.log("tempStoPrice", this.data.tempStoPrice)
        this.setData({
            useCoupon:that.data.tempUseCoupon,
            StoPrice:parseFloat(that.data.tempStoPrice),
            totalPrice:that.data.tempTotalPrice?that.data.tempTotalPrice:that.data.totalPrice,
            showStoreCoupons: false,
        },()=>{
            console.log('xiixixix----',that.data.tempTotalPrice,'hyuhuhuu----',that.data.totalPrice,'rrrrrr000-0----',that.data.StoPrice,'==类型==',typeof(that.data.StoPrice));
        })
        // console.log(this.data.comL, "dkdddiokdjd")
    },
    click_company(e) {
        var that = this
        let {
            index,
            item
        } = e.currentTarget.dataset
        if (that.data.totalPrice < item.exceedMoney && that.data.flags && that.data.comL.length != 1) {
            common.showToast('商品总额不能低于满减金额')
            return
        }
        if (that.data.flags && that.data.totalPrice < item.exceedMoney && that.data.comL.length == 1) {
            common.showToast('商品总额不能低于满减金额')
            return
        }
        if (!that.data.flags && item.isSelect != true) {
            common.showToast('此为单选，请先取消选中')
            return
        }
        for (var i = 0; i < this.data.comL.length; i++) {
            if (i == index) {// 当前点击的券 isSelect取反
                console.log('休息==',!this.data.comL[i].isSelect);
                this.data.comL[i].isSelect = !this.data.comL[i].isSelect
              
            } else {// 其余的券标识为false
                this.data.comL[i].isSelect = false
            }
        }
        if (!item.isSelect) {// 本次选中了
            console.log('aaa----',item.isSelect,'_++++_',this.data.comL);
            var useCoupon = true;
            var StoPrice = parseFloat(item.discountsMoney) //单选的优惠金额
            // var totalPrice = this.data.totalPrice.toFixed(2) - StoPrice

        } else {// 本次取消选中
            var useCoupon = false;
            console.log('bbbb----',item.isSelect,'_++++_',this.data.comL);
            var StoPrice = parseFloat(item.discountsMoney) //单选的优惠金额
            // var totalPrice = this.data.totalPrice + StoPrice
        }
        console.log('嘻嘻hhh',StoPrice);
        // console.log('ggghhh',totalPrice);
        this.setData({
            tempUseCoupon:useCoupon,
            tempStoPrice:StoPrice,
            // tempStoPrice:useCoupon?StoPrice:0,
            
            // tempTotalPrice:totalPrice,
            comL: this.data.comL
        }, () => {
            console.log(this.data.comL)
            var inde = this.data.comL.findIndex(t => t.isSelect == true)
            console.log(inde, "ddd")
            var coupObj = inde != -1 ? this.data.comL[inde] : ''
            console.log(coupObj, "coupObjcoupObj")
            that.setData({
                componyobjs: coupObj
            })
            if (this.data.comL.findIndex(targrt => targrt.isSelect == true) == -1) {
                that.setData({
                    flags: true
                })

            } else {
                that.setData({
                    flags: false
                })
            }
        })

    },
    checkTime() {
        // this.attached()

        this.setData({
            checkedTime: true
        })
    },
    // 优惠券关闭
    onStoreCouponosClose() {
        this.compnayClose()
    },
    compnayClose() {
        // console.log(this.data.comL, "关闭关闭")
        var companyTotal = 0
        for (var i = 0; i < this.data.comL.length; i++) {
            var item = this.data.comL[i]
            if (item.isSelect) {
                companyTotal = companyTotal + this.data.comL[i].discountsMoney
            }
        }
        for (var i = 0; i < this.data.comL.length; i++) {
            this.data.comL[i].isSelect = false
        }
        this.setData({
            storePrice: this.data.storePrice + companyTotal,
            StoPrice: 0,
            comL: this.data.comL,
            flags: true,
            showStoreCoupons: false,
            componyobjs: ''
        })
    },
    // 打开优惠券
    coup_open() {
        this.setData({
            showStoreCoupons: true
        })
    },
    // 店铺优惠券线上券
    copuStoreList() {
        var that = this
        var tempJson = {
            storeId: that.data.storeId,
            couponType: 1, //1线上券，2线下券
            token: that.data.token,
            userId: that.data.userInfo.id
        };
        common.wxRequest("/discountCoupon/getMyCouponForStoreByType", "post", tempJson, 'application/x-www-form-urlencoded', function (res) {
            console.log(res);
            if (res.status == 200) {


                var arr = []

                for (var i = 0; i < res.data.length; i++) {

                    res.data[i].beginTime = common.dateFormat('yyyy-MM-dd', res.data[i].beginTime)
                    res.data[i].finishTime = common.dateFormat('yyyy-MM-dd', res.data[i].finishTime)
                    res.data[i].isSelect = false
                    // console.log( res.data[i].exceedMoney)
                    if (that.data.storePrice - res.data[i].exceedMoney > 0) {
                        console.log(res.data[i].exceedMoney)
                        arr.unshift(res.data[i])
                    } else {
                        arr.push(res.data[i])
                    }
                }

                that.setData({
                    comL: arr
                }, () => {
                    console.log('默认---',that.data.comL);
                })
            }
        });
    },
    attached: function () {
        let t = new Date().getTime() + 1800000;
        let d = new Date(t);
        let theMonth = d.getMonth() + 1;
        let theDate = d.getDate();
        let theHours = d.getHours();
        let theMinutes = d.getMinutes();
        let start_day = this.ts_string(new Date().getTime());
        let end_day = this.ts_string(new Date().setDate(new Date().getDate() + this.data.range))
        //获取日期列表
        let date_list = this.getDiffDate(start_day, end_day);
        console.log(date_list, "attachedattachedattachedattached")
        this.setData({
            start_time: theHours
        })
        //获取时间列表 this.data.start_time, this.data.end_time, this.data.step
        let time_list = this.getTimeList(this.data.start_time, this.data.end_time, this.data.step);
        console.log(time_list, "attachedattachedattachedattached222222")
        this.setData({
            // date_time: [date_column, time_column],
            date_list: date_list,
            time_list: time_list,
        }, () => {
            console.log(this.data.time_list, "jjjggguuuu")
        })
        //动画
        this.animation = wx.createAnimation({
            duration: 300
        })
        //500rpx转成px this.data.date_list[0] +
        let dialoghpx = 800 / 750 * wx.getSystemInfoSync().windowWidth
        this.setData({
            dialogh: dialoghpx,
            selectDate: this.data.time_list[0]
        })
    },
    getDiffDate(start, end) {
        let startTime = new Date(start);
        let endTime = new Date(end);
        let dateArr = [];
        while ((endTime.getTime() - startTime.getTime()) >= 0) {
            dateArr.push(this.ts_string(startTime.getTime()));
            startTime.setDate(startTime.getDate() + 1);
        }
        return dateArr;
    },
    zfill(num, length) {
        return (Array(length).join('0') + num).slice(-length);
    },
    //把日期转换成xxxx-xx-xx的形式
    ts_string(timestamp) {
        let d = new Date(timestamp);
        let day = "";
        switch (d.getDay()) {
            case 1:
                day = "周一";
                break;
            case 2:
                day = "周二";
                break;
            case 3:
                day = "周三";
                break;
            case 4:
                day = "周四";
                break;
            case 5:
                day = "周五";
                break;
            case 6:
                day = "周六";
                break;
            case 0:
                day = "周日";
                break;
        }
        let string = (d.getFullYear()) + "-" +
            this.zfill((d.getMonth() + 1), 2) + "-" +
            this.zfill((d.getDate()), 2) + " (" + day + ")"
        return string
    },
    //获取时间区间列表，输入(起始时间，结束时间，步长)
    getTimeList(start, end, step) {
        let start_time = new Date();

        //设置起始时间
        start_time.setHours(start, 0, 0);
        console.log(start_time, "start");
        //设置结束时间
        let end_time = new Date();
        end_time.setHours(end, 0, 0);
        let startG = start_time.getTime(); //起始时间的格林时间
        let endG = end_time.getTime(); //起始时间的格林时间
        let step_ms = step * 60 * 1000;
        let timeArr = [];
        while (startG < endG) {
            let time = this.timeAdd(startG, step_ms);
            timeArr.push(time);
            startG += step_ms;
        }

        return timeArr;
    },
    timeAdd(time1, add) {
        var nd = new Date(time1); //创建时间对象
        //获取起始时间的时分秒
        var hh1 = nd.getHours();
        var mm1 = nd.getMinutes();
        if (hh1 <= 9) hh1 = "0" + hh1;
        if (mm1 <= 9) mm1 = "0" + mm1;
        nd = nd.valueOf(); //转换为毫秒数
        nd = nd + Number(add);
        nd = new Date(nd);
        var hh2 = nd.getHours();
        var mm2 = nd.getMinutes();
        if (hh2 <= 9) hh2 = "0" + hh2;
        if (mm2 <= 9) mm2 = "0" + mm2;
        var time = hh1 + ":" + mm1 + "-" + hh2 + ":" + mm2;
        return time; //时间段
    },
    change: function (e) {
        console.log("滑动")
        const val = e.detail.value;
        //val[0]表示选择的第一列序号，val[1]表示选择的第二列序号
        // this.data.date_list[val[0]] + 
        let select = this.data.time_list[val[1]]
        console.log(select);
        this.setData({
            selectDate: select
        })

    },
    showDialog() {
        this.setData({
            isTimeShow: true
        })
        //先向下移动dialog高度，然后恢复原位从而形成从下向上弹出效果
        this.animation.translateY(this.data.dialogh).translateY(0).step()
        this.setData({
            animation: this.animation.export()
        })
    },
    dimsss() {
        //从原位向下移动dailog高度，形成从上向下的收起效果
        this.animation.translateY(this.data.dialogh).step()
        this.setData({
            animation: this.animation.export()
        })
        //动画结束后蒙层消失
        setTimeout(() => {
            this.setData({
                checkedTime: false
            })
        }, 300)
    },
    cancel() {
        this.triggerEvent("cancel")
        this.dimsss()
    },
    confirm() {
        this.setData({
            checkedTime:false
        })
        // this.triggerEvent("confirm", {
        //     checkedTime: false
        // })
        // this.dimsss()
    },

    //查询店铺配送方式
    getPostType: function () {
        var that = this
        var tempJson = {
            storeId: that.data.storeId,
            userId: that.data.userInfo.id,
            // xpoint: that.data.xpoint,
            // ypoint: that.data.ypoint,
            // xpoint: "117.2852110862732",
            // ypoint: "34.80111369611973"
                   xpoint:that.data.newLongitude,
            ypoint:that.data.newLatitude,
        }
        // this.setData({
        //     loadingCount: this.data.loadingCount + 1,
        //     loadingSuccessCount: that.data.loadingSuccessCount - 1
        // })
        common.post('/store/getStorePostTypeForBuyUser', tempJson, function (res) {
            if (res.status === 200) {
                that.setData({
                    postPrice: res.data[0].price ? res.data[0].price : 0,
                    // totalPostType: res.data,
                    // postType: res.data[0] ? res.data[0].feeType : 1,
                    // postage: res.data[0].price ? res.data[0].price : 0,
                    // loadingSuccessCount: that.data.loadingSuccessCount + 1
                }, function () {
                    // that.selectComponent('#vanTabs').resize()
                })
            } else {
                // common.showRequestErrMsg(res)
            }
        }, function () {
            that.setData({
                loadingCount: that.data.loadingCount - 1
            })
        })
    },

    // 下单
    submit: common.throttleFunc(function (e) {
        const that = this
        console.log('postType---',that.data.postType);
        console.log(that.data.selectedAddr, "845661555")
        if (that.data.postType === '2' || that.data.postType === 2) {
            if (common.isEmptyString(that.data.pickUpSelfPhone)) {
                common.showToast('请输入手机号码')
            } else {
                if (that.data.hasSelectPAmount) { // 省级券

                    that.voucherPayFunc();
                } else { // 没券和市级券

                    that.normalPayFunc();
                }
            }
        } else {

            if (that.data.selectedAddr && that.data.postType == 1) {
                if (that.data.hasSelectPAmount) { // 省级券
                    console.log('已选中惠民券');
                    that.voucherPayFunc();
                } else { // 没券和市级券
                    console.log('不用券||市券');
                    that.normalPayFunc();
                }
            } else {
                common.showToast('您还未添加任何地址~')
            }
        }



    }, 2000),
    // 下单
    normalPayFunc() {
        // console.log( this.data.componyobjs," that.data.componyobjs.udcId")
        console.log('----',this.data.hasBuy,'++++',this.data.memeberSelect);

        // return
        this.setData({
            loadingCount: this.data.loadingCount + 1
        })
        const that = this
        const payment = that.data.storePrice + that.data.postage - (that.data.hasSelectPAmount || that.data.hasSelectCityPAmount) // 实付金额

        var StoPrice = parseFloat(that.data.StoPrice) //单选的优惠金额
        var calTotalPrice = that.data.totalPrice.toFixed(2) - StoPrice
        console.log('--1--',StoPrice,'--2--',typeof(StoPrice),'--3--',calTotalPrice);
        var cardDiscount = '';
        if(that.data.hasBuy || that.data.memeberSelect){
            cardDiscount = calTotalPrice*(100-that.data.cardVipJson.payRate*100)/100
        }
        const tempJson = {
            token: that.data.token,
            invitationCode: that.data.invitationCode || '',
            payType: 1,
            cardId: that.data.cardId,
            list: [{
                order: {
                    cardDiscountAmount:cardDiscount,
                    isBuyAnnualCard:(!that.data.hasBuy&&that.data.memeberSelect)?1:0,//是否同步开通会员卡  0不开通  1开通     
                    annualCardId:(!that.data.hasBuy&&that.data.memeberSelect)?that.data.cardVipJson.id:'', //  开通会员卡ID
                    deliveryTime: that.data.selectDate,
                    payment: that.data.totalPrice.toFixed(2),
                    userId: that.data.userInfo.id,
                    postFee: that.data.postage, //邮费
                    // buyerMessage: that.data.remark,
                    // remark: that.data.remark,
                    buyerMessage: that.data.commentValue,
                    remark: that.data.commentValue,
                    buyerNick: that.data.userInfo.userName,
                    storeId: that.data.storeId,
                    postType: that.data.postType, //1—商城配送;2—到店自提
                    orderType: 1, //商品订单1，活动订单2
                    cityCouponNo: that.data.cityCouponNo,
                    goldPrice: that.data.counts, //金豆抵扣
                    userDiscountCouponId: that.data.componyobjs ? that.data.componyobjs.udcId : '', //企业券线上
                    discountCoupons: that.data.discountCoupons
                    // discountCoupons:
                },
                items: that.data.items,
                ship: {
                    receiverName: that.data.receiverName || that.data.pickUpSelfName,
                    receiverPhone: '', //可以为空
                    receiverMobile: that.data.receiverMobile || that.data.pickUpSelfPhone,
                    receiverAddress: that.data.receiverAddress,
                    receiverZip: ''
                },
            }]
        };

        //创建订单
        if (that.data.radio == 1) {
            var url = '/order/createChinaumsOrderForH5'
        } else if (that.data.radio == 2) {
            var url = '/order/createChinaumsOrderForH5'
        }
        console.log('参数为——--',tempJson);

        common.postJson(url, tempJson, function (ret) {
            if (ret.status == 200) {
                console.log(ret.data, "jjjjjjj")
                // if (payment == 0 && that.data.postage == 0 && (!that.data.StoPrice && that.data.storePrice 0)||(!that.data.benefitPrice && that.data.storePrice <=0) {
                if (payment == 0 && that.data.postage == 0 && !that.data.StoPrice && !that.data.benefitPrice) {
                    wx.showToast({
                        title: '支付成功',
                        icon: 'none',
                        success: res => {
                            setTimeout(() => {
                                // 待支付
                                // packageC/pages/takeoutTobepaid/takeoutTobepaid

                                // if (that.data.cardId) {
                                //     wx.navigateTo({
                                //         url: '/pages/ScenicArea/NianCardOrder/index?titles=1',
                                //     })
                                // } else {
                                //     wx.navigateTo({
                                //         url: '/packageA/pages/Goods/goodsOrder/goodsOrderList/index?type=1',
                                //     })
                                // }
                            }, 1000)
                        }
                    })
                    return
                }


                // var tempJson = {
                //     userId: that.data.userInfo.id,
                //     token: that.data.token,
                //     orderId: ret.data[0].order.id,
                //     openid: that.data.openid,
                // }

                var tempJson = {
                    userId: that.data.userInfo.id,
                    token: that.data.token,
                    orderId: ret.data[0].order.id,

                    xcxOpenid: that.data.openid,
                }
                that.setData({
                    loadingCount: that.data.loadingCount + 1
                })
                if (that.data.radio == 1) {
                    // var urls = '/wxxcxPayForGoods'
                    var urls = '/wxxcxPayGoodsForFYPlatformChinaUms'
                } else if (that.data.radio == 2) {
                    var urls = '/wxxcxPayGoodsForFYPlatformChinaUms'
                }

                common.wxPayRequest(urls, that.data.radio == 1 ? tempJson : tempJsons, function (res) {
                    console.log(res, "lilili")
                    if (res.status !== 200) {
                        common.showRequestErrMsg(res)
                    } else {
                        //微信支付
                        wx.requestPayment({
                            'timeStamp': res.data.timeStamp,
                            'nonceStr': res.data.nonceStr,
                            'package': res.data.package,
                            'signType': res.data.signType,
                            'paySign': res.data.paySign,
                            'success': function (res) {
                                common.showToast('支付成功', 'success')
                                if (that.data.cardId != '') {
                                    wx.navigateTo({
                                        url: `/packageC/pages/takeoutTobepaid/takeoutTobepaid?orderId=${ret.data[0].order.id}`,
                                    })
                                } else {
                                    wx.navigateBack({
                                        delta: 1
                                    })
                                }

                            },
                            'fail': function (res) {
                                if (that.data.cardId != '') {
                                    wx.navigateTo({
                                        url: '/pages/ScenicArea/NianCardOrder/index?titles=1',
                                    })
                                } else {
                                    wx.redirectTo({
                                        url: '/packageA/pages/Goods/goodsOrder/goodsOrderList/index?type=1',
                                    })
                                }

                                if (res.errMsg === 'requestPayment:fail cancel') { } else {
                                    common.showToast(res.errMsg)
                                }
                            }
                        })
                    }
                }, function () {
                    that.setData({
                        loadingCount: that.data.loadingCount - 1
                    })
                })
            } else {
                common.showRequestErrMsg(ret)
            }
        }, function () {
            that.setData({
                loadingCount: that.data.loadingCount - 1
            })
        })
    },
    // 配送地址范围
    // deliveryAdress() {
    //     var that = this
    //     var tempJson = [
    //         {
    //             storeId: 1641,
    //             shipId: 472,
    //             xpoint: 117,
    //             ypoint: 37
    //         }
    //     ]
    //     common.postJson('/store/getStoreIsDeliveredList', tempJson, function (res) {
    //         if (res.status === 200) {

    //         } else {
    //             common.showRequestErrMsg(res)
    //         }
    //     }, function () {
    //         that.setData({
    //             loadingCount: that.data.loadingCount - 1
    //         })
    //     })
    // },


    onLoad(options) {
      console.log('options---',options);
        const that = this
        //获取胶囊位置
        this.attached()
        that.mapCtx = wx.createMapContext('myMap')
        qqmapsdk = new QQMapWX({
            //   key: 'W57BZ-JDB6X-XPA4H-Z76MI-73FF2-24BT4'
            key: 'SUOBZ-SJG6B-PQQUT-JL75Z-3F3Z5-AAFJ3' // 原P35BZ-K2WAS-GUZO7-6IRVW-IYBQV-ZUB6B
        });
        let capsule = wx.getMenuButtonBoundingClientRect()
        this.setData({
            height: capsule.height,
            top: capsule.top,
        })
        common.getLocalUserInfo(function (success, data) {
            if (success) {
                console.log(data,"5588444551",'---options--',options)
                console.log('最新的价格--', parseInt(options.totalPrice));
                that.setData({
                    userInfo: data.user,
                    token: data.token,
                    openid: data.openid,
                    // pickUpSelfName: data.user.realName,
                    pickUpSelfPhone: data.user.phone,
                    storeId: parseInt(options.storeId),
                    totalPrice: parseInt(options.totalPrice),
                    cardId: app.globalData.cardId,
                    storePriceAddress: options.storePrice ? parseFloat(options.storePrice) : -1
                }, () => {
                    // that.data.storePrice = that.data.totalPrice
                
                    // that.copuStoreList()
                   
                    that.getShopDes()
                    // that.getGoodsDes()
                    that.getCartNum() //商品列表
               
                    that.setData({
                        storePrice: that.data.totalPrice
                    })
                })

                if (!that.data.selectedAddr) {
                    // that.addressList() //地址列表
                }
                if (options.selectedAddr) {
                    console.log("1111111111111111111111111111111111111111")
                    // 已经选择地址的逻辑，当前逻辑是从选择地址列表返回
                    that.setData({
                        selectedAddr: options.selectedAddr,
                        receiverName: options.receiverName,
                        receiverMobile: options.receiverMobile,
                        receiverAddress: options.receiverAddress,
                        xpoint: options.longitude,
                        ypoint: options.latitude,
                        postPrice:options.postPrice,
                        StoPrice:options.StoPrice,
                        fixedPostPrice:options.postPrice,
                    })
                } else {
                    that.copuStoreList()
       that.addressList()
       that.getCardForTakeawayFunc();
                    console.log("22222222222222222222222222222222222222222")
                    // 默认进入 - 未选择地址，从下单页面进入
                    getApp().getLocation(function (data) {
                        console.log('经11纬度为---',data);
                        that.data.lon = data.longitude
                        that.data.lat = data.latitude
                        that.setData({
                          storeId: parseInt(options.storeId),
                            xpoint: data.longitude,
                            ypoint: data.latitude
                        }, function () {
                            // that.getPostType() //根据位置查询店铺配送方式
                        })
                    })
                }
            }
        }, true)

    },
    getCardForTakeawayFunc(){
        
        var that = this
        let tempJson = {
            storeId: that.data.storeId,
            // userId: that.data.userInfo.id,
            // token: that.data.token
        }

        common.post('/userAnnualCard/getCardForTakeawayRec', tempJson, function (res) {
            console.log('会员卡会员',res);
            if (res.status === 200) {
                var tempData = res.data;
                that.setData({
                    cardVipJson:res.data,
                    cardVipShow:res.data?true:false,
                },()=>{
                    
                    if(tempData==null){
                        console.log('嘻嘻嘻');
                        var json = {};
                        json.payRate = 1;
                        that.setData({
                            cardVipJson:json
                        })
                       
                    }
                })
                if(res.data){
                    that.isPayFunc(res.data.id);
                }
            
            } else {
                common.showRequestErrMsg(res)
            }
        }, function () {
           
        })
    },
    // 获取购物车数量
    getCartNum() {
        const that = this
        let tempJson = {
            storeId: that.data.storeId,
            userId: that.data.userInfo.id,
            token: that.data.token
        }
        common.wxRequest('/cart/listByStore', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                let totalPrice = 0;
                let totalPackingFee = 0;
                let totalNum = res.data.totalNum
                res.data.list.map((item, index) => {
                    totalPrice = item.num * item.price + totalPrice;
                    totalPackingFee = totalPackingFee + item.packingFee*item.num;
                })
                var storeprice;
                console.log(app.globalData.discount, "app.globalData.discountapp.globalData.discount")
                if (that.data.storePriceAddress == -1) {
                    storeprice = app.globalData.cardId ? (app.globalData.productprice) : (totalPrice * app.globalData.discount)
                    // that.getUserAssets()
                } else {
                    storeprice = that.data.storePriceAddress
                }

                let items = []
                res.data.list.map((item, index) => {
                    console.log(item, "1111111")
                    items.push({
                        dishFlavor: item.dishFlavor,
                        itemId: item.itemId,
                        num: item.num,
                        title: item.title,
                        price: item.price,
                        totalFee: (item.num * item.price),
                        picPath: item.image,
                    })
                })
                console.log(items)
    
        
                that.setData({
                  
                    goodList: res.data.list, //商品列表
                    cartNum: totalNum,
                    goodsCount: 0,
                    totalPrice,
                    totalPackingFee,
                    storePrice: storeprice,
                    items
                })

            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },

    //查询商品详情信息 13329 13330
    getGoodsDes() {
        const that = this
        let tempJson = {
            // itemId: that.data.itemId
            itemId: 13329
        }
        that.setData({
            loadingCount: that.data.loadingCount + 1,
            loadingSuccessCount: that.data.loadingSuccessCount - 1
        }, function () {
            common.post('/item/info', tempJson, function (res) {
                if (res.status === 200) {
                    var storeprice;
                    console.log(app.globalData.discount, "app.globalData.discountapp.globalData.discount")
                    if (that.data.storePriceAddress == -1) {
                        storeprice = app.globalData.cardId ? (app.globalData.productprice) : (res.data.price * app.globalData.discount)
                        that.getUserAssets()
                    } else {
                        storeprice = that.data.storePriceAddress
                    }
                    that.setData({
                        goodsInfo: res.data,
                        cityBenefitItemFlag: res.data.cityBenefitItemFlag,
                        benefitItemFlag: res.data.benefitItemFlag,
                        storePrice: storeprice,
                        storePriceTwo: app.globalData.cardId ? (app.globalData.productprice) : (res.data.price * app.globalData.discount),
                        price: res.data.price,
                        loadingSuccessCount: that.data.loadingSuccessCount + 1
                        // totalMoney:
                    }, () => {
                        // var isNum =     //是整数，则返回true，否则返回false
                        if (typeof that.data.storePrice == 'number' && that.data.storePrice % 1 == 0) {
                            that.setData({
                                isNum: true
                            })
                        } else {
                            that.setData({
                                isNum: false
                            })
                        }

                    })
                } else {
                    common.showRequestErrMsg(res)
                }
            }, function () {
                that.setData({
                    loadingCount: that.data.loadingCount - 1
                })
            })
        })
    },
    //查询店铺信息
    getShopDes() {
        var that = this
        let tempJson = {
            storeId: that.data.storeId
        }
        this.setData({
            loadingCount: this.data.loadingCount + 1,
            loadingSuccessCount: that.data.loadingSuccessCount - 1
        })
        common.post('/store/info', tempJson, function (res) {
            if (res.status === 200) {
                let markers = [
                    {
                        id: 2,
                        latitude: res.data.ypoint,
                        longitude: res.data.xpoint,
                        iconPath: 'http://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/icon/po.png',
                        width: 20,
                        height: 20,
                        callout: {
                            content: '据您0.5km',
                            color: '#000',
                            fontSize: 12,
                            borderWidth: 2,
                            borderRadius: 5,
                            borderColor: '#ffff',
                            bgColor: '#fff',
                            padding: 2,
                            display: 'ALWAYS',
                            textAlign: 'center'
                        },
                    }
                ]
                that.setData({
                    storeInfo: res.data,
                    longitude: res.data.xpoint,
                    latitude: res.data.ypoint,
                    markers: markers,
                    loadingSuccessCount: that.data.loadingSuccessCount + 1
                })
            } else {
                common.showRequestErrMsg(res)
            }
        }, function () {
            that.setData({
                loadingCount: that.data.loadingCount - 1
            })
        })
    },
    goBack() {
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2]; //上一个页面
        // 从朋友圈进入的时候，页面栈为空，这里需要判断是否有上个页面
        if (prevPage) {
            wx.navigateBack({
                delta: 1
            })
        } else {
            wx.redirectTo({
                url: '/pages/index/index',
            })
        }
    },
    // 地址列表
    addressList() {
        const that = this
        const tempJson = {
            storeId:that.data.storeId,
            userId: that.data.userInfo.id,
            token: that.data.token
        }
        common.post('/user/ship/listForStoreTakeaway', tempJson, function (res) {
            if (res.status === 200) {
                let obj = ''
                console.log(res, "55555")
                if (Array.isArray(res.data) && res.data.length) {
                     // isDefault为1,就立刻返回,不在往下遍历
                     obj = res.data.find((v) => v.deliveredFlag == 1)
                    }
                    console.log('--333333-',obj,'---类型',typeof(obj));
                    // return
                    if(obj){
                   
                        console.log('默认地址复制---',obj);
                        that.setData({
                            selectedAddr: obj.receiverAddress,
                            receiverName: obj.receiverName,
                            receiverMobile: obj.receiverMobile,
                            receiverAddress: obj.receiverAddress,
                            newLatitude:obj.ypoint,
                            newLongitude:obj.xpoint,
                        },()=>{
                            that.getPostType();
                        })
                    }

                
          
            } else {
                common.showRequestErrMsg(res)

            }
        })
    },



    onChange(e){
        let {value} = e.detail
        this.setData({
          commentValue: value
      } )
      },
      goBackFunc() {
        wx.navigateBack({
          delta: 1,
        })
      },  
      onRadioChange(event) {
          console.log('event--', event.detail);
        this.setData({
          radioValue: event.detail=="1"?0:"1",
        },()=>{
            console.log('---radioValue--',this.data.radioValue);
        });
      },
      selectMemeberFunc(){
       
          var that = this;
          console.log('tt---',that.data.memeberSelect);
          that.setData({
            memeberSelect:that.data.memeberSelect==true?false:true
        },()=>{
            console.log('最终选择状态',that.data.memeberSelect);
        })
      },
      seePrivilegeFunc(){
        if(this.data.hasBuy){
            this.data.cardVipJson.annualCardId = this.data.cardVipJson.id;
                var objs =JSON.stringify(this.data.cardVipJson) 
                console.log('222',objs);
            wx.navigateTo({
                url:'/packageA/pages/indexnian/indexni?obj=' + encodeURIComponent(objs),
            })
        }else{
           // 

            let url = `/pages/myNian/payCard/payCard?cardId=${this.data.cardVipJson.id}&distributorId=${this.data.cardVipJson.managerId}`
            common.tiao_Zhuan(url)
        }
},
  // 判断是否支付
  isPayFunc(idx) {
    var that = this
    common.get('/userAnnualCard/checkUserBoughtCard', {
        userId: this.data.userInfo.id,
        cardId: idx,
        token: this.data.token
    }, res => {
        console.log(res)

        that.setData({
            hasBuy:res.status === 1?true:false,
            memeberSelect:res.status === 1?true:false,
        },()=>{
            console.log('ssss---',that.data.hasBuy);
        })
        // if (res.status === 1) {
           
        //     // common.showToast(res.msg)
        //     // that.cardsList()
        // }
    })
},

   



 
})